<?php
namespace Library\Dal\Driver\Mysql;

class MysqlAdapter implements \Library\Dal\AdapterInterface
{
    protected $_resource;
    protected $_config;
    
    public $isConnected = false;
    
    public function __construct($settings)
    {
    	if (!is_array($settings))
		{
			$config = \Library\Platform::getConfig();
			
			$settings = array(
				'server' => $config['database'][$settings]['server'],
				'username' => $config['database'][$settings]['username'],
				'password' => $config['database'][$settings]['password'],
				'database' => $config['database'][$settings]['database']
			);
		}
		
        $this->_config = $settings;
    }
	
	public function getLastId()
	{
		return $this->_resource->lastInsertId();
	}
    
    public function getConnection()
    {
        if ( ! $this->_resource instanceof \PDO )
        {
            $this->connect();
        }
        
        return $this->_resource;
    }
    
    public function connect()
    {
        $this->_resource = new \PDO( "mysql:dbname=" . $this->_config['database'] . ";host=" . $this->_config['server'], 
             $this->_config['username'], 
             $this->_config['password'],
             array(
                 \PDO::ATTR_PERSISTENT => true,
                 \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
             ) 
         );
            
        if ( $this->_resource !== false )
        {
            $this->isConnected = true;
        }
    }
    
    public function getAttr($key)
    {
        return $this->_resource->getAttribute($key);
    }
    
    public function setAttr($key, $value)
    {
        return $this->_resource->setAttribute($key, $value);
    }
    
    public function prepare($query)
    {
        $st = $this->getConnection()->prepare($query);
		
        if ($query instanceof \Library\Dal\Query || $query instanceof \Library\Dal\Driver\Mysql\ActiveRecord)
		{
			foreach($query->getParameters() as $parameter)
	        {
	            $st->bindParam($parameter['0'], $parameter['1'], $parameter['2']);
	        }
		}
        
        return $st;
    }

    public function query($query)
    {
        $st = $this->prepare($query);
	 	   
        $st->execute();
        
        return $st;
    }

    public function fetchAll($query)
    {
        return $this->Query($query)->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function fetchRow($query)
    {
        return $this->Query($query)->fetch(\PDO::FETCH_ASSOC);
    }

    public function countRows($query)
    {
        
    }
    
    public function close()
    {
        $this->_resource = null;
    }
}